using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using System.Text;
using System.Collections;
using System.Resources;
using System.Security.Principal;
using Microsoft.MediaCenter.UI;
using ClipShow2.MediaTypes;

namespace ClipShow2.Storage
{
    [Serializable]
    public enum SortOptions {ByDate, ByDateReverse, ByName};
    [Serializable]
    public class Settings
    {
        private SortOptions _mySortOptions = SortOptions.ByDateReverse;
        private bool _isTransparent = true;
        public Settings()
        {
        }

        [XmlAttribute]
        public SortOptions MediaSortOption
        {
            get { return (_mySortOptions); }
            set { _mySortOptions = value; }
        }

        [XmlAttribute]
        public bool Transparent
        {
            get { return (_isTransparent); }
            set { _isTransparent = value; }
        }
    }

    public class StorageEngine
    {
        private const string THUMBNAIL_DIR = "Thumbnails";
        private const string MEDIALIB_DIR = "MediaSources";
        private const string APP_WORK_DIR = "clipShowV2";
        private const string TAGS_DIR = "TagSettings";

        public StorageEngine()
        {
            
        }

        public static void Initialize()
        {
            if (!Directory.Exists(GetUserProfileDir()))
            {
                Directory.CreateDirectory(GetUserProfileDir());
            }

            if (!Directory.Exists(GetApplicationSettingsDir()))
            {
                Directory.CreateDirectory(GetApplicationSettingsDir());
            }

            if (!Directory.Exists(GetLibraryDir()))
            {
                Directory.CreateDirectory(GetLibraryDir());
            }

            if (!Directory.Exists(GetThumbnailDir()))
            {
                Directory.CreateDirectory(GetThumbnailDir());
            }

            if (!Directory.Exists(GetTagSettingsDir()))
            {
                Directory.CreateDirectory(GetTagSettingsDir());
            }
        }

        private static string UserName()
        {
            string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
            return(userName.Replace("\\", "_"));
        }
        public static string CreateASX(ArrayList source, string playListName)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("<asx version=\"1.0\">");
            sb.AppendFormat("<title>{0}</title>", playListName);
            string thumbnailUrl = "";
            foreach (ClipShowMetadata med in source)
            {
                if (thumbnailUrl.Equals(""))
                {
                    if (File.Exists(med.ThumbnailUrl))
                    {
                        thumbnailUrl = med.ThumbnailUrl;
                    }
                }
                sb.AppendFormat("<entry><title>{0}</title><ref href=\"{1}\"/><author>{2}</author></entry>",
                    med.Title, med.Url, med.Author);
            }
            sb.AppendFormat("</asx>");

            try
            {
                string filePath = String.Format("{0}\\{1}.asx", GetAsxTargetDir(), playListName);
                TextWriter writer = new StreamWriter(filePath);
                writer.Write(sb.ToString());
                writer.Close();
                string asxThumbnail = String.Format("{0}\\{1}.jpg", GetAsxTargetDir(), playListName);
                if (File.Exists(thumbnailUrl))
                {
                    File.Copy(thumbnailUrl, asxThumbnail, true);
                }
                return (filePath);
            }
            catch (SystemException se)
            {
                throw se;
            }
        }

        public static void PersistSettings(Settings source)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Settings));

            string writeFilePath = String.Format("{0}\\Settings.xml",
                GetUserProfileDir());
            TextWriter writer = new StreamWriter(writeFilePath);
            serializer.Serialize(writer, source);
            writer.Close();
        }

        public static Settings GetSettings()
        {
            try
            {
                string settingsFilePath = string.Format("{0}\\Settings.xml",
                    GetUserProfileDir());
                if (File.Exists(settingsFilePath))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(Settings));
                    FileStream fs = new FileStream(settingsFilePath, FileMode.Open);
                    Settings result = (Settings)serializer.Deserialize(fs);
                    fs.Close();
                    return (result);
                }
                else
                {
                    return (new Settings());
                }
            }
            catch
            {
                return (new Settings());
            }
        }

        public static ClipShowContent GetMediaLibrary(string sourceFilePath)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(ClipShowContent));
            FileStream fs = new FileStream(sourceFilePath, FileMode.Open);
            ClipShowContent result = (ClipShowContent)serializer.Deserialize(fs);
            fs.Close();
            return (result);
        }

        public static string[] GetTagFile(string fileName, string[] defaultResult)
        {
            try
            {
                string tagDir = GetTagSettingsDir();
                string sourceFilePath = String.Format("{0}\\{1}", tagDir, fileName);
                XmlSerializer serializer = new XmlSerializer(typeof(string[]));
                FileStream fs = new FileStream(sourceFilePath, FileMode.Open);
                string[] result = (string[])serializer.Deserialize(fs);
                fs.Close();
                return (result);
            }
            catch
            {
                return defaultResult;
            }
        }

        public static string PersistMediaLibrary(ClipShowContent cm)
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(ClipShowContent));

                string writeFilePath = String.Format("{0}\\{1}.xml",
                    GetLibraryDir(), cm.ContentSourceName);

                if (File.Exists(writeFilePath))
                {
                    try
                    {
                        File.Delete(writeFilePath);
                    }
                    catch
                    {
                    }
                }
                TextWriter writer = new StreamWriter(writeFilePath);
                serializer.Serialize(writer, cm);
                writer.Close();
                return (writeFilePath);
            }
            catch (SystemException se)
            {
                throw se;
            }
        }

        public static void PersistTagFile(string[] source, string fileName)
        {
            string tagDir = GetTagSettingsDir();
            XmlSerializer serializer = new XmlSerializer(typeof(string[]));

            string writeFilePath = String.Format("{0}\\{1}", tagDir, fileName);
            if (!File.Exists(writeFilePath))
            {
                TextWriter writer = new StreamWriter(writeFilePath);
                serializer.Serialize(writer, source);
                writer.Close();
            }

        }

        private static string GetAsxTargetDir()
        {
            string myFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
            string result = String.Format("{0}Users\\Public\\Videos\\clipShow playlists", Path.GetPathRoot(myFolder));

            if (!Directory.Exists(result))
            {
                Directory.CreateDirectory(result);
            }
            return (result);
        }
        public static string GetThumbnailDir()
        {
            string filePath = String.Format("{0}\\{1}",
                GetUserProfileDir(),
                THUMBNAIL_DIR);
            return (filePath);
        }

        public static string GetTagSettingsDir()
        {
            string filePath = String.Format("{0}\\{1}",
                GetUserProfileDir(),
                TAGS_DIR);
            return (filePath);
        }

        private static string GetLibraryDir()
        {
            string filePath = String.Format("{0}\\{1}",
                GetUserProfileDir(),
                MEDIALIB_DIR);
            return (filePath);
        }
        private static string GetApplicationSettingsDir()
        {
            string filePath = String.Format("{0}\\{1}",
                Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                APP_WORK_DIR);
            return (filePath);
        }

        private static string GetUserProfileDir()
        {
            string filePath = String.Format("{0}\\{1}",
                GetApplicationSettingsDir(),
                UserName());
            return (filePath);
        }

        public static string MediaLibraryPath(string contentLibName)
        {
            string readFilePath = String.Format("{0}\\{1}.xml",
                GetLibraryDir(), contentLibName);
            return (readFilePath);
        }
    }
}
